package com.cebbank.yyi.springbootapp.jingtang.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.cebbank.yyi.springbootapp.jingtang.ResponseInfo;
import com.cebbank.yyi.springbootapp.jingtang.dto.FileOperatorParams;
import com.cebbank.yyi.springbootapp.jingtang.dto.RcDocForFileDto;
import com.cebbank.yyi.springbootapp.jingtang.entity.DownloadFileInfo;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FileUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    public static final String VERSION_SUFFIX = "Z5";

    private FileUtil() {

    }

    private final static String LOCAL_PATH = "C:\\tcz\\";

    private final static String SLASH = "\\";

    public static String downloadFile(String token, DownloadFileInfo downloadFileInfo, String rcId) throws Exception {
        String filePath = downloadFileInfo.getFilePath();
        ResponseInfo responseInfo = RequestUtil.downloadFile(filePath, token);
        if (responseInfo.getOriginalFileName() == null) {
            log.error("{} 下载的为null", rcId);
        }
        String fileName = StrUtil.isEmpty(responseInfo.getOriginalFileName()) ? downloadFileInfo.getFileName() : responseInfo.getOriginalFileName();
        String renameFile = fileName.replaceAll("#", "_").replaceAll("\\+", "_").replaceAll(" ", "_").replaceAll(",", "_").replaceAll("%", "_").replaceAll("&", "_");
        log.info("当前获取到的文件名称为:{}", renameFile);
        String localFileName = LOCAL_PATH + rcId + SLASH + renameFile;
        File file = new File(localFileName);
        // 判断目录是否存在，不存在则创建目录

        File parent = new File(file.getParent());
        if (!parent.exists()) {
            parent.mkdir();
        }

        // 判断文件是否存在, 不存在创建文件
        if (!file.exists()) {
            if (file.createNewFile()) {
                // 获取请求结果输入流
                InputStream rInputStream = responseInfo.getResponseBody().byteStream();
                // 创建读取字节流的byte数组
                byte[] buffer = new byte[500];
                int areRead;
                // 创建文件输出流
                FileOutputStream outputStream = new FileOutputStream(file);
                // 使用输入流读取字节，在输出到文件
                while ((areRead = rInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, areRead);
                }
                System.err.printf("文件下载成功:[%s]\n", localFileName);
                rInputStream.close();
                outputStream.close();
                responseInfo.getResponseBody().close();
            }
        }
        return renameFile;
    }

    public static boolean uploadMainFile(FileOperatorParams fileOperatorParams, String rcId) {
        String filePath = LOCAL_PATH + rcId + SLASH + fileOperatorParams.getDocName();
        String responseStr = RequestUtil.uploadMainFile(filePath, fileOperatorParams.getDocId(), fileOperatorParams.getDirectoryType());
        System.err.println(responseStr);
        if (StrUtil.isNotEmpty(responseStr) && responseStr.contains("docUrl")) {
            Gson gson = new Gson();
            RcDocForFileDto rcDoc = gson.fromJson(responseStr, RcDocForFileDto.class);
            if (StrUtil.isNotBlank(rcDoc.getDocUrl())) {
                System.err.printf("主文件文档[%s]上传成功！\n", fileOperatorParams.getDocName());
                return true;
            } else {
                log.error("主文件文档[{}]上传失败，docUrl为空！\n", fileOperatorParams.getDocName());
                return false;
            }
        } else {
            log.error("主文件文档[{}]上传失败，响应结果为：[{}]\n", fileOperatorParams.getDocName(), responseStr);
            return false;
        }
    }

    public static boolean uploadAttachmentFile(FileOperatorParams fileOperatorParams, String fileId) {
        String filePath = LOCAL_PATH + fileId + SLASH + fileOperatorParams.getDocName();
        String responseStr = RequestUtil.uploadAttachmentFile(filePath, fileOperatorParams.getDocId());
        System.err.printf("附件文档[%s]上传结果：[%s]\n", fileOperatorParams.getDocName(), responseStr);
        if (StrUtil.isNotEmpty(responseStr) && responseStr.contains("attachment")) {
            System.err.printf("附件文档[%s]上传成功！\n", fileOperatorParams.getDocName());
            return true;
        } else {
            log.error("附件文档[{}]上传失败，响应结果为：[{}]\n", fileOperatorParams.getDocName(), responseStr);
            return false;
        }
    }

    public static String uploadAttachmentFile2(FileOperatorParams fileOperatorParams, String rawId) {
        String filePath = LOCAL_PATH + rawId + SLASH + fileOperatorParams.getDocName();
        String responseStr = RequestUtil.uploadAttachmentFile2(filePath, fileOperatorParams.getDocId());
        System.err.printf("附件文档[%s]上传结果：[%s]\n", fileOperatorParams.getDocName(), responseStr);
        if (StrUtil.isNotEmpty(responseStr) && responseStr.contains("attachment")) {
            System.err.printf("附件文档[%s]上传成功！\n", fileOperatorParams.getDocName());
            return responseStr;
        } else {
            log.error("附件文档[{}]上传失败，响应结果为：[{}]\n", fileOperatorParams.getDocName(), responseStr);
            return "";
        }
    }

    public static void docEsSync(FileOperatorParams fileOperatorParams) {
        String responseStr = RequestUtil.docEsSync(fileOperatorParams.getDocId());
        System.err.println(responseStr);
//        if (responseStr.contains("attachment")) {
//            System.err.printf("文档[%s]上传成功！", fileOperatorParams.getDocName());
//        } else {
//            System.err.printf("文档[%s]上传失败，响应结果为：[%s]", fileOperatorParams.getDocName(), responseStr);
//        }
    }

    public static String getSnowId() {
        return IdUtil.getSnowflakeNextIdStr() + VERSION_SUFFIX;
    }

    public static String getVersion() {
        return VERSION_SUFFIX;
    }
}
